/*
 * @Author: liu wang wang
 * @Date: 2020-07-13 09:58:18
 * @LastEditTime: 2020-07-13 10:26:25
 * @LastEditors: liu wang wang
 * @Description: url处理函数库
 * @FilePath: \st-sdk-js\src\utils\url.ts
 */
import { isDate, isPlainObject } from '../tools'

function encode(val: string): string {
    return encodeURIComponent(val)
        .replace(/%40/g, '@')
        .replace(/%3A/gi, ':')
        .replace(/%24/g, '$')
        .replace(/%2C/gi, ',')
        .replace(/%20/g, '+')
        .replace(/%5B/gi, '[')
        .replace(/%5D/gi, ']')
}

export function bulidURL(url: string, params?: any) {
    if (!params) {
        return url
    }

    const parts: string[] = []

    Object.keys(params).forEach((key) => {
        let val = params[key]
        if (val === null || typeof val === 'undefined') {
            return
        }
        let values: string[]
        if (Array.isArray(val)) {
            values = val
            key += '[]'
        } else {
            values = [val]
        }
        values.forEach((val) => {
            if (isDate(val)) {
                val = val.toISOString()
            } else if (isPlainObject(val)) {
                val = JSON.stringify(val)
            }
            parts.push(`${encode(key)}=${encode(val)}`)
        })
    })

    let serializedParams = parts.join('&')

    if (serializedParams) {
        const markIndex = url.indexOf('#')
        if (markIndex !== -1) {
            url = url.slice(0, markIndex)
        }

        url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams
    }
    return url
}